package com.pg.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * Druid连接池工具类
 */
public class JdbcUtils {
	/**
	 * 定义成员变量 DataSource
	 */
	private static DataSource ds;
	static {
		Properties p = new Properties();
		try {
//			//外网
//			p.put("url", "jdbc:nds://10.88.4.135:18701/v_18701_eip_sc?appname=app_eip_sc");
//			// 内网测试
//			p.put("url", "jdbc:postgresql://10.89.33.104:19201/msidb");
//			// 内网正式
//			p.put("url", "jdbc:postgresql://10.89.33.108:19200/msidb");
			// 本地测试
			p.put("url", "jdbc:postgresql://8.8.12.12:19200/msidb");

			//外网驱动
//			p.put("driverClassName", "sgcc.nds.jdbc.driver.NdsDriver");
			 //内网驱动
			p.put("driverClassName", "org.postgresql.Driver");
			p.put("username", "postgres");
//			p.put("password", "Pggc@1234");
			p.put("password", "postgres");
			p.put("maxWait", "6000");
			p.put("queryTimeout", "1000");
			p.put("validationQuery", "select 1");
			ds = DruidDataSourceFactory.createDataSource(p);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 3 获得链接
	public static Connection getConnection() throws SQLException {
		return ds.getConnection();
	}

	// 4 释放资源
	public static void close(Statement stat, Connection conn) {
		if (stat != null) {
			try {
				stat.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(ResultSet rs, Statement stat, Connection conn) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (stat != null) {
			try {
				stat.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	// 5 获得连接池
	public static DataSource getDataSource() {
		return ds;
	}
}
